import React from "react";
import {Modal, Button, Icon} from "tinper-bee";
import Table from "bee-table";
import 'bee-table/build/Table.css';
import FormControl from "bee-form-control";
import 'bee-form-control/build/FormControl.css';
import "./index.less";
import pen from "./../../assets/image/pen.png";
import InputNumber from "bee-input-number";
import 'bee-input-number/build/InputNumber.css';
import {queryIndexOfPlan }from "./workgantt.config";
import { vendorsFmtDate, vendorsDanger as danger, vendorsSetDateLoop } from 'utils/config.js';
export default (params) => (WrappedComponent) => class TargetModal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showModal: false,
            columns : [
                { title: "序号", dataIndex: "index", key: "index", width: 50 , render :(text, record, index)=>{
                    return index + 1;
                }},

                { title: "指标编码", dataIndex: "code", key: "code", width: '20%', render :(text, record, index)=>{
                    return(
                        <div>
                            { text }
                        </div>
                    )
                }},

                { title: "指标名称", dataIndex: "name", key: "name", width:'20%', render :(text, record, index)=>{
                    return(
                        <div>
                            { text }
                        </div>
                    )
                }},
                { title: "数量", dataIndex: "expectTotal", key: "expectTotal", width: '20%', render :(text, record, index)=>{
                    return(
                        <div>
                           {this.state.from === "browse" ? 
                                <div> {text}</div> :
                                record && this.formControl(text, record, index)}
                        </div>
                    )
                }},
                { title: "计量单位", dataIndex: "unit", key: "unit", width: '20%', render :(text, record, index)=>{
                    return(
                        <div>
                            { text }
                        </div>
                    )
                }},

                { title: "备注", dataIndex: "memo", key: "memo", width: '20%', render :(text, record, index)=>{
                    return(
                        <div>
                            { text }
                        </div>
                    ) 
                }},
                { title: "操作", dataIndex: "operation", key: "operation", width: "5%",  render :(text, record, index)=>{
                    return(
                        <div>
                            {this.state.from === "browse"?
                                null: <div className={'addTarget'} onClick = {()=>this.delete(text, record, index)}>
                                移除
                            </div>
                            }
                        </div>
                    )
                }}
            ],
            tableData:[],
            initalData :[],
            searchValue:'',
            pkPlan :'',
            from :'',
            deleteDataArrExist:[]
        };
    }

 
    delete = (text, record, index)=>{
        console.log(record)
        let deleteDataArrExist =[... this.state.deleteDataArrExist];
        if(record.pkPlanIndex){
            deleteDataArrExist.push(record.pkPlanIndex)//删除的已经存在于数据库里的数据主键
        }
        this.state.tableData.splice(index, 1);
     
        this.setState({
            tableData: [...this.state.tableData],
            initalData : [...this.state.initalData],
            deleteDataArrExist : [...deleteDataArrExist]
        })
    }

    formControl = (text, record, index) =>{
        return(
            <div
                className = {"attrStyle"}
                onMouseOver = {()=>this.showPencil(index)} 
                onMouseLeave = {()=>this.hidePencil(index)}
                onClick = {()=>this.editCurAttr(text, record, index)}
            >
               {
                    record["expectTotal"]["input"] ? 
                    this.inputHtml(text, record, index): 
                    <div>
                        {text.value}
                        { record["expectTotal"]["hasImg"] ? <img src={pen}/> : null}
                    </div>
               }
            </div>
        )
    }
    showPencil = (index) =>{
        this.state.tableData[index]["expectTotal"]["hasImg"] = true;
        this.setState({
            tableData : this.state.tableData
        })
    }

    hidePencil = (index) =>{
        this.state.tableData[index]["expectTotal"]["hasImg"] =false;
        this.setState({
            tableData : this.state.tableData
        })
    }
    editCurAttr = (text, record, index) =>{
        this.state.tableData[index]["expectTotal"]["input"] =  true;

        this.setState({
            tableData:this.state.tableData
        }) 
    }
    inputHtml = (text, record, index) =>{
        return (
            <InputNumber
                value={text.value}
                onChange = {(value)=> this.textChange(value, index)}
                onBlur = { ()=>{
                    this.state.tableData[index]["expectTotal"]["input"] = null;
                    this.setState({
                        tableData:  this.state.tableData
                    })
                }}
                min = {0}
                precision = {3}
            />
        )
    }
    textChange = (value, index) =>{
        
        if(value){
            let exp = new RegExp(/^(\d{1,10})(\.(\d{0,3}))?$/, "g");
            let flag = exp.test(value);
            if(!flag){
                danger({'text':"最多整数为十位，小数位3位"})
                return;
            }
        }
        this.state.tableData[index]["expectTotal"].value = value;
        this.setState({
            tableData : [...this.state.tableData],
            initalData : [...this.state.tableData],
        })
    }
    filterTableData = (value) =>{
        let data =[];
        let initalData = [...this.state.initalData];
        initalData.map((item, index)=>{
            if(item.name.toString().indexOf(value) !== -1 || item.code.toString().indexOf(value) !== -1){
                data.push(item)
            }
        })
        return data;
    }
    onSearch = (value)=>{
        let searchValue = value.target? value.target.value : value;
        this.setState({
            searchValue
        }, ()=>{
            let data = this.filterTableData(searchValue);
            this.setState({
                tableData : [...data],
                deleteDataArrExist:[]
            })
        })
       
    }
    init=()=>{
        queryIndexOfPlan({pkPlan : this.state.pkPlan, 'isAjax': 1, 'ieStamp': new Date().getTime()}).then((res)=>{
            if (res.data.resultCode !== 'busi_ex') {
                let data = this.handleTableDataStructor(res.data.result);
                if(this.state.from === "browse"){
                    if(this.state.columns[this.state.columns.length-1].key ==="operation"){
                        this.state.columns.splice(this.state.columns.length-1 , 1)
                    }
                }
                
                this.setState({
                    tableData: [...data],
                    initalData : [...data],
                    columns :  [...this.state.columns]
                })
            }
        })
    }

    handleTableDataStructor = (data) => {
        data.map((item, index)=>{
            item["expectTotal"] =this.state.from ==="browse"?  item.expectTotal : {value : item.expectTotal};
            item.key = index;
            item.index = index;
          
        })
        return data;
    }

    //通过子组件控制高阶组件的状态state
    setCurStateByWrapCom = (params)=>{
        if(params.tableData){
            params.tableData.map((item, index)=>{
                item.expectTotal = item.expectTotal ? item.expectTotal : {value : ''};
               
            })
        }
        
        this.setState(params, ()=>{
            document.getElementById("bee-table-uid").style.width = "100%"
            if(this.state.pkPlan && !this.state.tableData.length){
                this.init();
            }
        })
    }
    setShowModal = ()=>{
        this.setState({
            showModal : true
        }, ()=>{
            document.getElementById("bee-table-uid").style.width = "100%"
            if( this.state.pkPlan){
                this.init();
            }
        })
    }
    handleDataStructor = (data) =>{
        data.map((item, index)=>{
            item["changeFlag"] = item.changeFlag;
        })
        return data;
    }
    close = (from) =>{
        this.setState({
            showModal : false,
        }, ()=>{
            if(from ==="confirm"){
                
                let tableData = this.handleDataStructor(this.state.tableData);
                this.refs["[object Object]"].handlerSaveTarget({
                    targetArr: [...tableData],
                    deleteTargetArr:[...this.state.deleteDataArrExist],
                    indexNumber : tableData.length
                })
            }
            this.setState({
                tableData:[],
                initalData :[],
                deleteDataArrExist : [],
                searchValue:'',
                pkPlan :'',
                from :'',
            })
        })
    }
    chooseTarget=()=>{
        this.setState({
            showModal : false
        },()=>{
            this.props.setCurStateByWrapCom({
                showChooseModal: true,
                hasSelectedValue: [...this.state.tableData],
                from : 'chooseTarget'
            })
        })
    }

    render() {
        let {
            showModal,
            columns,
            tableData,
            searchValue,
            from
        } = this.state;
        return (
            <div>
               <WrappedComponent {...this}  ref = {this}/>
                <Modal
                    backdrop = {false}
                    show = {showModal}
                    onHide = {()=>this.close("cancel")}
                    size = {"xlg"}
                >
                    <Modal.Header closeButton className={"targetModalheader"}>
                        <Modal.Title>指标</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        {
                            from === "browse"? null:
                            <div  className={'search-header'}>
                                <div className={'search-header-search'}>
                                    <FormControl
                                        value={searchValue}
                                        onChange = {(value)=>this.onSearch(value)}
                                        placeholder="请输入指标编码或名称"
                                        emptyText={() => '暂无数据'}
                                        showClose = {true}
                                        className={'searchFormControl'}
                                    />
                                    <Icon className="search-icon" type='uf uf-search-light' />
                                </div>
                                <Button  className={'chooseTarget'} onClick={()=>this.chooseTarget()}>选择指标</Button>
                            
                            </div>
                        }
                        <Table
                            columns={columns}
                            data = {tableData}
                            showRowNum = {true}
                            className = {"scroll-table-target"}
                        />
                    </Modal.Body>
                    <Modal.Footer className = {'buttonTarget'}>

                        {
                            this.state.from === "browse"? null:
                            <Button 
                                onClick={()=>this.close("confirm")} 
                                className = {"confirm"} 
                                bordered
                            >确定</Button>
                        }
                    </Modal.Footer>
                </Modal>
            </div>
        );
    }
}
